package com.my.controller;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.my.constants.MessageRabbitConstants;
import com.my.dto.MessageDTO;
import com.my.dto.WecomReceiveMsgDTO;
import com.my.util.aes.AesException;
import com.my.util.aes.WXBizJsonMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author sjx
 * @date 2025/2/10 14:01
 */
@Slf4j
@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Value("${wecom.msg.token}")
    private String token;
    @Value("${wecom.msg.encodingAesKey}")
    private String encodingAesKey;
    @Value("${wecom.corpId}")
    private String corpId;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/receiveMsg/callback")
    public String receiveMsgGet(@RequestParam("msg_signature")String msgSignature,
                             @RequestParam("timestamp")String timestamp,
                             @RequestParam("nonce")String nonce,
                             @RequestParam("echostr")String echostr) {

        String messageJson;
        try{
            WXBizJsonMsgCrypt wxBizJsonMsgCrypt = new WXBizJsonMsgCrypt(token,encodingAesKey,corpId);
            messageJson = wxBizJsonMsgCrypt.VerifyURL(msgSignature,timestamp,nonce,echostr);
        } catch (AesException e) {
            throw new RuntimeException(e.getMessage());
        }
        log.info("配置成功,返回:{}",messageJson);
        return messageJson;
    }

    @PostMapping("/receiveMsg/callback")
    public String receiveMsgPost(@RequestParam("msg_signature")String msgSignature,
                                   @RequestParam("timestamp")String timestamp,
                                   @RequestParam("nonce")String nonce,
                                   @RequestBody String requestBody) {
        try{
            ObjectMapper objectMapper = new XmlMapper();

            WXBizJsonMsgCrypt wxBizJsonMsgCrypt = new WXBizJsonMsgCrypt(token,encodingAesKey,corpId);

            WecomReceiveMsgDTO wecomReceiveMsg = objectMapper.readValue(requestBody, WecomReceiveMsgDTO.class);
            log.info("转换的json:{}",wecomReceiveMsg);
            String messageJson = wxBizJsonMsgCrypt.VerifyURL(msgSignature,timestamp,nonce,wecomReceiveMsg.getEncrypt());
            log.info("消息接收成功:{}",messageJson);
            MessageDTO messageDTO = objectMapper.readValue(messageJson,MessageDTO.class);
            String msgType = messageDTO.getMsgType();
            //接收对象为文本
            if(!StringUtils.hasText(msgType) || !"text".equalsIgnoreCase(msgType)){
                log.warn("接收格式错误,必须是文本(text),当前接收格式:{}",msgType);
                return messageJson;
            }

            String content = messageDTO.getContent();
            if(!StringUtils.hasText(content) ||
                content.length() < 10 ||
                content.length() > 30||
                !org.apache.commons.lang3.StringUtils.isNumeric(content)){
                log.warn("接收数据有误,当前接收数据:{}",content);
                return messageJson;
            }

            rabbitTemplate.convertAndSend(MessageRabbitConstants.WECOM_MSG_EXCHANGE_NAME,MessageRabbitConstants.WECOM_MSG_ROUTE_KEY, JSON.toJSONString(messageDTO));
            return messageJson;
        } catch (AesException e) {
            throw new RuntimeException(e.getMessage());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
